package com.asia.order.utils;

import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.xml.bind.DatatypeConverter;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
 * 加密\解密
 * @ClassName: EncodeExample 
 * @author: 
 * @date: 2017年11月20日 下午5:30:24
 */
@SuppressWarnings("restriction")
public class EncodeExample {
	public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
   private KeySpec ks;
   private SecretKeyFactory skf;
   private Cipher cipher;
   SecretKey key;
   private static String myEncryptionKey = "111111111111111111111111111111111111111111111111";
	public EncodeExample()throws Exception {
       this.ks = new DESedeKeySpec(DatatypeConverter.parseHexBinary(myEncryptionKey));
       this.skf = SecretKeyFactory.getInstance("DESede");
       this.key = this.skf.generateSecret(this.ks);
       this.cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
	}
	public String encryption(String encrypstr) throws Exception{
		try{
			this.cipher.init(Cipher.ENCRYPT_MODE,this.key);
			byte[] byteFina = this.cipher.doFinal(encrypstr.getBytes());
			BASE64Encoder encoder = new BASE64Encoder();
 			String strMi = encoder.encode(byteFina);
 			return strMi;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	public String dencryption(String dencrypstr)throws Exception{
		try{
			BASE64Decoder base64Decoder = new BASE64Decoder();
			byte[] byteMi = base64Decoder.decodeBuffer(dencrypstr);
			this.cipher.init(Cipher.DECRYPT_MODE, this.key);
			byte[] byteFina = cipher.doFinal(byteMi);
			String strMing = new String(byteFina, "ascii");
			return strMing;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
}

